const config = require('./config');
const ioc = require('socket.io-client');
const _ = require('lodash');

let socket;

class UploadFile {
    constructor() {
        this._callback = {};
    }

    async init() {
        if (_.isEmpty(config.url))
            throw new Error('缺少服务器网址');
        if (_.isEmpty(config.name))
            throw new Error('缺少截图程序的名称，请到config.json文件配置');
        if (_.isEmpty(config.token))
            throw new Error('缺少截图程序的Token，请到config.json文件配置');

        let url = `${config.url}?token=${config.token}&name=${config.name}`;
        console.log('url', url);
        socket = ioc(url);

        socket.on('connect_error', err => {
            console.error(err);
        });

        socket.on('disconnect', () => {
            console.error('断开连接');
            process.exit(0);
        });

        socket.on('connect', () => {
            console.log('成功连接到 控制端');
        });

        //服务器下发配置
        socket.on('config', config => {
            if (this._callback['ready'])
                this._callback['ready'](config);
        });

        socket.on('screenshot_anchor', message => {
            if (this._callback['screenshot_anchor'])
                this._callback['screenshot_anchor'](message);
        });

        socket.on('restart', () => {
            if (this._callback['restart'])
                this._callback['restart']();
        });
    }

    on(name = '', callback) {
        if (!name || name.length === 0)
            throw new Error('事件名称不能为空');
        this._callback[name] = callback;
    }

    /**
     * 发送数据
     * @param name
     * @param data
     */
    emit(name, data) {
        socket.emit(name, data);
    }
}

//
module.exports = UploadFile;